package models

import (
	"strings"

	"github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
)

var (
	Banners map[string]*Banner
	// O       orm.Ormer
)

type Banner struct {
	Id         int    `orm:"column(id);pk"`
	Link       string `orm:"size(1024)"`
	Img_url    string `orm:"size(1024)"`
	Sort_order int
	Status     int
	Created_at string `orm:"size(19)"`
	Updated_at string `orm:"size(19)"`
}

func (u *Banner) TableName() string {
	return "yxx_banner"
}

// func getOrmer() orm.Ormer {
// 	if O == nil {
// 		println("O is nil")
// 		O = orm.NewOrm()
// 	}
// 	return O
// }
func init() {
	// O = orm.NewOrm()
	// orm.RegisterModel(new(Banner))
	orm.RegisterModelWithPrefix("kppw_", new(Banner))
	Banners = make(map[string]*Banner)
}

func GetBannerOne(id int) *Banner {

	oo := getOrmer()
	// o := orm.NewOrm()
	banner := Banner{Id: id}
	oo.Read(&banner)
	return &banner
}

func GetBannerAll() []*Banner {

	oo := getOrmer()
	bannerList := []*Banner{}

	qs := oo.QueryTable("kppw_yxx_banner")
	qs.All(&bannerList)

	return bannerList
}

func (u Banner) Search(filter map[string]string) []*Banner {

	oo := getOrmer()
	bannerList := []*Banner{}

	qs := oo.QueryTable("kppw_yxx_banner")
	println(filter["link"])
	if filter["link"] != "" {
		println("filter link ")
		qs.Filter("link__icontains", filter["link"])
	}

	qs.All(&bannerList)

	return bannerList
}

func (u Banner) Search2(filter map[string]string) []*Banner {

	// oo := getOrmer()
	bannerList := []*Banner{}

	qb, _ := orm.NewQueryBuilder("mysql")
	where := make([]string, 0, 4)
	qb.Select("*").
		From("kppw_yxx_banner")
		// Where("link like '%" + filter["link"] + "%'").

	if filter["link"] != "" {
		where = append(where, "link like '%"+filter["link"]+"%'")
	}
	if filter["status"] != "" {
		where = append(where, "status = "+filter["status"]+"")
	}
	if filter["start_time"] != "" {
		where = append(where, "created_at >= '"+filter["start_time"]+"'")
	}
	if filter["end_time"] != "" {
		where = append(where, "created_at <= '"+filter["end_time"]+"'")
	}

	if len(where) > 0 {
		where_str := strings.Join(where, " and ")
		qb.Where(where_str)
	}

	qb.OrderBy("created_at").Desc().Limit(10).Offset(0)
	// 导出 SQL 语句
	sql := qb.String()
	println(sql)
	// 执行 SQL 语句
	o := orm.NewOrm()
	o.Raw(sql).QueryRows(&bannerList)
	return bannerList
}
